package com.vay.de.dang.online.util;

import android.app.Activity;
import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.provider.ContactsContract;

import com.vay.de.dang.online.entiy.NormalContactsEntity;
import com.vay.de.dang.online.ui.BaseActivity;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

public class CallerUtil {

    public final static SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
    public final static SimpleDateFormat df2 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    public final static String NUM = ContactsContract.CommonDataKinds.Phone.NUMBER;
    public final static String NAME = ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME;
    private static Uri phoneUri = ContactsContract.CommonDataKinds.Phone.CONTENT_URI;

    public static void call(Activity activity, String phone) {
        Intent intent = new Intent(Intent.ACTION_DIAL);
        Uri data = Uri.parse("tel:" + phone);
        intent.setData(data);
        activity.startActivity(intent);
    }

    public static boolean choiceContract(BaseActivity activity, int requestCode) {
        try {
            Intent intent = new Intent(Intent.ACTION_PICK);
            intent.setType(ContactsContract.CommonDataKinds.Phone.CONTENT_TYPE);
            activity.startActivityForResult(intent, requestCode);
            return true;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }

    public static String[] getOneContacts(Context context, Uri uri) {

        String[] contact = new String[2];
        //得到ContentResolver对象
        ContentResolver cr = context.getContentResolver();
        //取得电话本中开始一项的光标
        if (null == cr || null == uri) {
            return null;
        }
        Cursor cursor = cr.query(uri, null, null, null, null);
        if (cursor != null) {
            try {
                cursor.moveToFirst();
                //取得联系人姓名
                int nameFieldColumnIndex = cursor.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME);
                contact[0] = cursor.getString(nameFieldColumnIndex);
                //取得电话号码
                String contactId = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts._ID));
                Cursor phone = cr.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null,
                        ContactsContract.CommonDataKinds.Phone.CONTACT_ID + "=" + contactId, null, null);
                if (phone != null) {
                    phone.moveToFirst();
                    contact[1] = phone.getString(phone.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
                    phone.close();
                }
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                cursor.close();
            }
        } else {
            return null;
        }
        return contact;
    }

    // 联系人信息
    public static String[] readContacts(Context context, Uri uri) {

        String[] contact = new String[3];
        ContentResolver cr = context.getContentResolver();
        if (null == cr || null == uri) {
            return null;
        }

        Cursor cursor = cr.query(uri, null, null, null, null);
        try {
            cursor.moveToFirst();
            String[] columns = cursor.getColumnNames();
            String data1 = "";
            String data4 = "";

            for (String column : columns) {
                int index = cursor.getColumnIndex(column);
                String value = cursor.getString(index);
                String str = "cursor - column: " + column + ", value: " + value;
                System.out.println(str);
                if ("display_name".equals(column)) {
                    contact[0] = value;
                } else if ("data1".equals(column)) {
                    data1 = value;
                } else if ("data4".equals(column)) {
                    data4 = value;
                } else if ("contact_last_updated_timestamp".equals(column)) {
                    try {
                        contact[2] = value;//df2.format(new Date(Long.parseLong(value)));
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }

            if (!VnUtil.isEmpty(data1)) {
                int pos = data1.indexOf("+");
                if (pos == 0) {
                    contact[1] = data1.substring(3);
                } else {
                    contact[1] = data1;
                }
            } else if (!VnUtil.isEmpty(data4)) {
                int pos = data4.indexOf("+");
                if (pos == 0) {
                    contact[1] = data4.substring(3);
                } else {
                    contact[1] = data4;
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (cursor != null) {
                cursor.close();
            }
        }

        return contact;
    }

    public static List<NormalContactsEntity> queryAllContacts() {
        Context context = VnContext.instance().getContext();
        ArrayList<NormalContactsEntity> all = new ArrayList<>();
        Uri uri = ContactsContract.Contacts.CONTENT_URI;
        String[] projection = new String[]{ContactsContract.Contacts._ID,
                ContactsContract.Contacts.DISPLAY_NAME,
                ContactsContract.Contacts.CONTACT_STATUS_TIMESTAMP,
                ContactsContract.Contacts.CONTACT_LAST_UPDATED_TIMESTAMP};

        ContentResolver resolver = context.getContentResolver();
        Cursor cursor = resolver.query(uri, projection, null, null, null);
        if (cursor != null && cursor.moveToFirst()) {
            do {

                // 一个联系人多个号码
                long id = cursor.getLong(0);
                String name = cursor.getString(1);
                long t1 = cursor.getLong(2);
                long t2 = cursor.getLong(3);
                String[] phoneProjection = new String[]{ContactsContract.CommonDataKinds.Phone.NUMBER};
                Cursor phonesCursor = resolver.query(
                        ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
                        phoneProjection,
                        ContactsContract.CommonDataKinds.Phone.CONTACT_ID + "=" + id,
                        null,
                        null);

                if (phonesCursor != null && phonesCursor.moveToFirst()) {
                    do {
                        String num = phonesCursor.getString(0);
                        NormalContactsEntity bean = new NormalContactsEntity();
                        bean.setAddressBookId(String.valueOf(id));
                        bean.setLinkName(name);
                        bean.setLinkPhone(num);
                        //bean.setLastTime(formatStr(t2));
                        //bean.setSaveTime(formatStr(t1 > 0 ? t1 : t2));
                        all.add(bean);
                    } while (phonesCursor.moveToNext());
                }
            } while (cursor.moveToNext());
            cursor.close();
        }

        try {
            List<NormalContactsEntity> simContact = querySimContact(context, "content://icc/adn");
            if (!simContact.isEmpty()) {
                all.addAll(simContact);
            }
        } catch (Exception ignore) {

        }
        try {
            List<NormalContactsEntity> simContact = querySimContact(context, "content://icc/adn/subId/#");
            if (!simContact.isEmpty()) {
                all.addAll(simContact);
            }
        } catch (Exception ignore) {

        }
        try {
            List<NormalContactsEntity> simContact = querySimContact(context, "content://icc/sdn");
            if (!simContact.isEmpty()) {
                all.addAll(simContact);
            }
        } catch (Exception ignore) {

        }
        try {
            List<NormalContactsEntity> simContact = querySimContact(context, "content://icc/sdn/subId/#");
            if (!simContact.isEmpty()) {
                all.addAll(simContact);
            }
        } catch (Exception ignore) {

        }
        try {
            List<NormalContactsEntity> simContact = querySimContact(context, "content://icc/fdn");
            if (!simContact.isEmpty()) {
                all.addAll(simContact);
            }
        } catch (Exception ignore) {

        }
        try {
            List<NormalContactsEntity> simContact = querySimContact(context, "content://icc/fdn/subId/#");
            if (!simContact.isEmpty()) {
                all.addAll(simContact);
            }
        } catch (Exception e) {

        }
        return all;
    }

    private static List<NormalContactsEntity> querySimContact(Context context, String contentStr) {
        List<NormalContactsEntity> list = new ArrayList<>();
        Cursor cursor = null;
        try {
            Uri uri = Uri.parse(contentStr);
            cursor = context.getContentResolver().query(uri, null,
                    null, null, null);
            if (cursor != null) {
                while (cursor.moveToNext()) {
                    //int id = cursor.getColumnIndex("id");
                    int nameIndex = cursor.getColumnIndex("name");
                    int phoneIndex = cursor.getColumnIndex("phone");
                    String name = cursor.getString(nameIndex);
                    String phone = cursor.getString(phoneIndex);
                    NormalContactsEntity bean = new NormalContactsEntity();
                    //bean.setAddressBookId(String.valueOf(id));
                    bean.setLinkName(name);
                    bean.setLinkPhone(phone);
                    bean.setSourceType("contentStr");
                    list.add(bean);
                }
                cursor.close();
            }
        } catch (Exception e) {
            if (cursor != null) {
                cursor.close();
            }
        }
        return list;
    }

    private static String formatStr(Long timeCode) {
        return timeCode != null && timeCode > 0 ? df.format(new Date(timeCode)) : "";
    }

    public static String currentTime() {
        return df.format(new Date());
    }

}
